import sys
import os
sys.path.append(os.getcwd()) # 将当前目录加入sys.path

from ui.Ui_MainWindow import Ui_MainWindow
from plot.figureplot import FigurePlot
from PyQt5 import QtCore, QtGui, QtWidgets

class mainWindow(QtWidgets.QMainWindow, Ui_MainWindow):    
    # 切换ui
    main2arima = QtCore.pyqtSignal()
    main2informer = QtCore.pyqtSignal()
    openCalculate = QtCore.pyqtSignal()

    arimaisTrained = False
    informerisTrained = False
    
    def __init__(self):
        # super().setupUi(Dialog)
        super(mainWindow, self).__init__()
        self.setupUi(self)
        
        self.file = None #要处理的文件
        # 注释
        self.file = 'data\\sentiment.csv'
        self.Primarykey = 'UMCSENT'
        #buttons
        self.browseButton.clicked.connect(self.browsefile)
        self.openButton.clicked.connect(self.openfile)
        self.downloadButton.clicked.connect(self.download)
        self.uploadButton.clicked.connect(self.upload)
        # self.reloadButton.setStyleSheet("background-color: green");
        # self.reloadButton.clicked.connect(self.reload)
        #lineedit
        self.lineEdit.setPlaceholderText("file(*.csv, *.xlsx, *xls, *.txt)...")
        #pages
        self.page1Button.clicked.connect(self.page1)
        self.page2Button.clicked.connect(self.page2)
        self.page3Button.clicked.connect(self.page3)        
        self.page4Button.clicked.connect(self.page4)
        #uiButtons
        self.applyButton.clicked.connect(self.apply)
        self.trainButton.clicked.connect(self.train)
        self.calculateButton.clicked.connect(self.calculate)
        self.selectallButton.clicked.connect(self.selectAll)
        
    def page1(self):
        self.stackedWidget.setCurrentIndex(0)   
    def page2(self):
        self.stackedWidget.setCurrentIndex(1)    
    def page3(self):
        self.stackedWidget.setCurrentIndex(2)
    def page4(self):
        self.stackedWidget.setCurrentIndex(3)

    def browsefile(self):
        openfile = QtWidgets.QFileDialog.getOpenFileName(None, '', '', 'CSV Files(*.csv);;Excel files(*.xlsx, *xls);;Text File(*.txt);;All Files(*)')
        self.lineEdit.setText(openfile[0])
        self.lineEdit.setReadOnly(True)
        self.file = openfile[0]
           
    def openfile(self):
        filepath = self.lineEdit.text()
        if os.path.isfile(filepath):
            self.file = filepath
            msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Information, 'Content', 'File open!')
            msg_box.exec_()
        else:
            msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, 'Waring', 'File does not exist!')
            msg_box.exec_()
    
    def showGraphics(self):
        dr1 = FigurePlot()
        dr1.LineChart(self.file, self.Primarykey) #折线图
        # 加载的图形（FigureCanvas）先放在GraphicsScene中，再将GraphicsScene放到GraphicsView中
        graphicsscene_1 = QtWidgets.QGraphicsScene() 
        graphicsscene_1.addWidget(dr1) 
        self.graphicsView_1.setScene(graphicsscene_1) 
        self.graphicsView_1.show()
    
    def upload(self):
        self.lineEdit.setPlaceholderText(self.file)
        # 注释
        self.PrimarykeylineEdit.setPlaceholderText(self.Primarykey)
        self.outsampleCheck.setChecked(True)
        self.insampleCheck.setChecked(True)
        if self.visualCheck.isChecked() & self.showdataCheck.isChecked():
            self.visual()
            self.showdata()
        elif self.visualCheck.isChecked():
            self.visual()
        elif self.showdataCheck.isChecked():
            self.showdata()
        else:
            return

    def download(self):
        #保存图片
        pass
        
    def visual(self):
        if self.file is None: #如果文件不存在
            msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, 'Waring', 'Please open a file!')
            msg_box.exec_()
        else:
            self.showGraphics() # 给文件画图
    
    def showdata(self):
        if self.file is None: #如果文件不存在
            msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, 'Waring', 'Please open a file!')
            msg_box.exec_()
        else:
            # 显示文件
            with open(self.file,'r') as f:
                my_txt=f.read()
                self.textEdit.setPlainText(my_txt)
    
    def apply(self):
        self.insampleCheck.isChecked(True)
        self.outsampleCheck.isChecked(True)
        self.Primarykey = self.PrimarykeylineEdit.text()
            
    def train(self):
        if self.arimaCheck.isChecked():
            self.arimaCheck.setStyleSheet("color:blue")
            self.arimaisTrained = True
            self.main2arima.emit()
        if self.informerCheck.isChecked():
            self.informerCheck.setStyleSheet("color:blue")
            self.informerisTrained = True
            self.main2informer.emit()
    
    def calculate(self):
        if self.arimaisTrained | self.informerisTrained:
            # 通过controller打开calculate界面，默认计算所有已经了训练的模型的误差
            self.openCalculate.emit()
        else:
            msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, 'Waring', 'Please train the model first.')
            msg_box.exec_()
            if (self.mfeCheck.isChecked() | self.maeCheck.isChecked() | self.mapeCheck.isChecked() | self.mpeCheck.isChecked() | self.mseCheck.isChecked() | self.sseCheck.isChecked() | self.smseCheck.isChecked() | self.rmseCheck.isChecked() | self.nmseCheck.isChecked()) == False:
                msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, 'Waring', 'Please select a error at least.')
                msg_box.exec_()
            else:
                self.openCalculate.emit()

    def selectAll(self):
        self.mfeCheck.setChecked(True)
        self.maeCheck.setChecked(True)
        self.mapeCheck.setChecked(True)
        self.mpeCheck.setChecked(True)
        self.mseCheck.setChecked(True)
        self.sseCheck.setChecked(True)
        self.smseCheck.setChecked(True)
        self.rmseCheck.setChecked(True)
        self.nmseCheck.setChecked(True)